<template>
    <el-row v-if="!loading&&firstIn" class="business-tab">
      <new-business v-if="!busId&&typeObj.type!=='business'" :cid="cid" :cdrCall="cdrCall" :callId="callId" v-on:event="businessEvent" :cacheId="cacheId" :custInfo="custInfo" :callInfo="callInfo"></new-business>
      <temporary-business v-if="item&&item.isStartStep" :detail="item" v-on:event="businessEvent" :cacheId="cacheId" :relatedBusinessShow="relatedBusinessShow"></temporary-business>
      <business-info v-if="item&&!item.isStartStep" :detail="item" :typeObj="typeObj" v-on:event="businessEvent" :callScreen="callScreen" :fixed="fixed" :showHistory="showHistory" :relatedBusinessShow="relatedBusinessShow" :cacheId="cacheId"></business-info>
      <history v-if="showHistory&&item" :item="item"></history>
      <history-table v-if="showHistoryTable" :cid="cid" :callScreen="callScreen" :title="$t('business.businessHistory')"></history-table>
      <!-- 关联工单 -->
      <history-table v-if="showbusRelatedTable" :type="'related'" :businessNumbers="newBusinessNumbers" :cid="cid" :callScreen="callScreen" :title="$t('webchat.relationBusiness')"></history-table>
    </el-row>
</template>
<script>
  import BusinessInfo from './BusinessInfo.vue'
  import History from './History.vue'
  import NewBusiness from './NewBusiness.vue'
  import TemporaryBusiness from './TemporaryBusiness.vue'
  import {getCache} from '@/utils/m7Utils.js'
  export default {
    name: 'BusinessSum',
    data () {
      return {
        loading: true,
        firstIn: false,
        newBusinessNumbers:this.businessNumbers
      }
    },
    props: {
      busId: String,
      refresh: String,
      typeObj: {
        type: Object,
        default: function () {
          return {
            type: '',
            tabType: ''
          }
        }
      },
      custInfo: {type: Object, default: function () { return {} }},
      callInfo: {type: Object, default: function () { return {} }},
      cid: String, // 客戶id
      showHistory: {type: Boolean, default: false},
      showHistoryTable: {type: Boolean, default: false},
      showbusRelatedTable: {type: Boolean, default: false},
      link: {type: String, default: ''},
      linkData: {
        type: Object,
        default: function () {
          return {}
        }
      },
      cacheId: {type: String, default: ''}, // 缓存工单信息的id
      cdrCall: {type: Boolean, default: false},
      callId: String,
      callScreen: {type: Boolean, default: false}, // 工单组件在dialog中则传true
      reload: {type: Number, default: 0},
      fixed: {type: String, default: ''}, // 工单吸顶
      relatedBusinessShow: {type: Boolean, default: true},//详情中不能再点击详情
      businessNumbers: {type: Array, default: ()=>[]} //关联工单
    },
    provide: function () {
      return {
        link: this.link
      }
    },
    components: {
      BusinessInfo,
      History,
      NewBusiness,
      TemporaryBusiness
    },
    computed: {
      item () {
        let item
        let busId = this.busId
        if (busId) {
          item = this.$store.state.business['current'].businessAction[this.busId]
        } else {
          item = ''
        }
        return item
      }
    },
    methods: {
      getServerUrl () { // 获取当前坐席所在的pbx
        let pbxid = this.$store.state.session.user.pbx
        let curpbx = ''
        let assDomain = ''
        if (pbxid) {
          curpbx = getCache('accountPbx', pbxid)
          assDomain = curpbx.assAddr
        }
        return assDomain
      },
      isStartStep (stepId) {
        let step = getCache('businessFlowStep', stepId)
        if (step && step.isBegin) {
          return true
        } else {
          return false
        }
      },
      fetchData () {
        let self = this
        if (this.refresh === 'business' || !this.refresh) {
          this.firstIn = true
        }
        Promise.all([
          this.$store.dispatch('getCache', {type: 'businessFlowStep'}),
          this.$store.dispatch('getCache', {type: 'businessFlow'}),
          this.$store.dispatch('getCache', {type: 'agents'}),
          this.$store.dispatch('getCache', {type: 'custTmpls'})
        ]).then(() => {
          self.loading = false
        })
      },
      businessEvent (eventData) {
        let eventType = eventData.event
        let data = eventData.data
        let currentId = this.$store.state.cti.globalLet.currentCallSheetId
        if(data.form){
          data.form.existAttach = false
          for(var key in data.form){
            if(data.form[key] instanceof Array){
              if(data.form[key].length>0&&data.form[key][0].name){
                data.form.existAttach = true
              }
            }
          }
          for(var key in data.form.actionFields){
            if(data.form.actionFields[key] instanceof Array){
              if(data.form.actionFields[key].length>0&&data.form.actionFields[key][0].name){
                data.form.existAttach = true
              }
            }
          }
        }
       
        if (eventType === 'addBusinessTask') {
          if(this.callScreen){
            data.form.createMode = 'call'
          }else{
            data.form.createMode = this.$route.path.split('/')[2]
          }
          let id = this.$route.path.split('/')[4]
          if ((this.link === 'call') || (this.callScreen && currentId)) { // 来电，去电，待处理 ||  外呼弹屏，全部里面的暂存工单，用于通话记录导出关联工单
            data.form.callId = id
            if (this.callScreen && currentId) { // 外呼弹屏用currentCallSheetId
              data.form.callId = currentId
            }
            if (this.$store.state.cti.globalLet.isCalling && currentId === data.form.callId) { // 通话中新建工单，把当前的通话信息传递过去
              let phoneData = this.$store.state.cti.globalLet.phone_data
              data.form.Channel = phoneData._curChannel
              data.form.pbx = phoneData.pbx_in_ip
              data.form.url = this.getServerUrl()
            }
            Object.assign(data.form, this.linkData)
          } else if (this.link === 'webchat') {
            data.form.linkWebchat = id
          } else if (this.link === 'mail') {
            data.form.linkMail = id
          }

          this.$store.dispatch('addBusinessTask', data.form).then((res) => {
            eventData.data._id = res
            this.$emit('event', eventData)
            // 工单新建成功，删除该缓存
            if (data.form._id === undefined) {
              // id为undefined是新建工单组件冒出的事件
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId)
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId + 'nextAction')
            }
          })
        } else if (eventType === 'addTempBusinessTask') {
          if(this.callScreen){
            data.form.createMode = 'call'
          }else{
            data.form.createMode = this.$route.path.split('/')[2]
          }
          if ((this.link === 'call') || (this.callScreen && currentId)) { // 来电，去电，待处理 ||  外呼弹屏，全部里面的暂存工单，用于通话记录导出关联工单
            data.form.callId = this.$route.path.split('/')[4]
            if (this.callScreen && currentId) { // 外呼弹屏用currentCallSheetId
              data.form.callId = currentId
            }
            if (this.$store.state.cti.globalLet.isCalling && currentId === data.form.callId) { // 通话中新建工单，把当前的通话信息传递过去
              let phoneData = this.$store.state.cti.globalLet.phone_data
              data.form.Channel = phoneData._curChannel
              data.form.pbx = phoneData.pbx_in_ip
              data.form.url = this.getServerUrl()
            }
          }
          if (this.link === 'mail') {
            data.form.linkMail = this.$route.path.split('/')[4]
          }

          let stepCache = {}
          stepCache._id = data.stepCacheCurId ? data.stepCacheCurId : ''
          stepCache.actionId = data.form.nextAction
          let actionFields = data.form.actionFields ? data.form.actionFields : null
          data.form.stepCache = Object.assign(stepCache, actionFields)
          this.$store.dispatch('addTempBusinessTask', data.form).then((res) => {
            eventData.data._id = res
            this.$message.success(this.$t('business.businessTempSuccess'))
            this.$emit('event', eventData)
            // 工单暂存成功，删除该缓存
            if (data.form._id === undefined) {
              // id为undefined是新建工单组件冒出的事件
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId)
              this.$store.commit('business/DELETE_BUS_CACHE', this.cacheId + 'nextAction')
            }
          })
        } else if (eventType === 'stepAction') {
          this.$store.dispatch('excuteBusinessStepAction', data.form).then((res) => {
            this.$emit('event', eventData)
            // 工单动作执行成功，删除该缓存
            this.$store.commit('business/DELETE_BUS_CACHE', this.item._id + 'action')
          })
        } else if (eventType === 'stepActionTemp') {
          if(data.dataForm){
            data.dataForm.existAttach = false
            for(var key in data.dataForm){
              if(data.dataForm[key] instanceof Array){
                if(data.dataForm[key].length>0&&data.dataForm[key][0].name){
                  data.dataForm.existAttach = true
                }
              }
            }
          }
          this.$store.dispatch('saveTempStepInfo', data.dataForm).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('business.businessTempSuccess'))
            } else {
              this.$message.error(res.message)
            }
            this.$emit('event', eventData)
          })
        } else if (eventType === 'commentAction') {
        } else if (eventType === 'backAction') {
          this.$store.dispatch('excuteBusinessBackAction', data.form).then(() => {
            this.$emit('event', eventData)
            this.$store.commit('business/DELETE_BUS_CACHE', this.item._id + 'back')
          })
        } else if (eventType === 'changeBusinessMaster') {
          this.$emit('event', eventData)
        }
      }
    },
    watch: {
      refresh () {
        if (this.refresh === 'business' || !this.refresh) {
          this.firstIn = true
        }
      },
      reload (cur, old) {
        this.loading = true
        this.$nextTick(() => {
          this.fetchData()
        })
      },
      businessNumbers () {
        this.newBusinessNumbers = this.businessNumbers
      }
    },
    beforeCreate: function () {
      this.$options.components.HistoryTable = require('@/components/business-modules/business/HistoryTable.vue').default
    },
    beforeMount () {
      this.fetchData()
    }
  }
</script>
<style lang="stylus">
  @import '../../../../assets/common.styl'
  .at-text
    color $c-pink
</style>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .el-row
    font-size 14px
    line-height 18px
    .add-ramark
      font-size 16px
      line-height 20px
      margin-left 26px
      span
        height 20px
        line-height 20px
      i
        display inline-block
        width 20px
        height 20px
        background-color  $c-main
        margin-right 8px
  .business-tab
    padding 20px 20px
</style>